#!/bin/bash

#采集的时间
get_time=$(date +%Y%m%d%H%M%S)
#采集cpu信息
cpu_info() {
	top -bn 1|awk '/^%Cpu/{print $2,$4,$8}'|while read  us sy  idle
	do
		#得到使用的cpu比率
		used_cpu=$( echo "scale=2;100 - $idle" | bc )
		#采集信息存放到日志文件，同时屏幕输出
		echo "$get_time  user process: $us  system process: $sy  idle: $idle used: $used_cpu" | tee -a /var/log/performance_usage.log
	done
}

#采集内存信息
mem_info() {
	free -m|awk '/^Mem/{print $2,$3,$4,$5,$6,$7}'|while read  total used free shared buff_cache available
	do
		echo "$get_time total_mem: $total M available_mem: $available free_mem: $free used_mem: $used_mem buff_cache: $buff_cache shared: $shared"|tee -a /var/log/performance_usage.log
	done 

}
#采集磁盘和分区的使用信息
disk_info() {
	#总共有多少磁盘和磁盘的大小
	disk_total=$(lsblk |grep "^sd"|awk '{print $1,$4}')
	#分区的信息
	 df -Th|egrep "/$|/home$|boot$"|awk '{print $3,$4,$5,$6,$7}'|while read size used free used_percent part_name
	do
		echo "$get_time disk size: $size  used: $used free: $free used_percent: $used_percent part_name: $part_name  disk_total: $disk_total"|tee -a /var/log/performance_usage.log
	done
}

#采集进程的信息
process_info() {
	#显示cpu使用率最高的前5个进程
	#cpu_top_5=$( ps aux --sort=-%cpu | head -n 6 | tail -n 5)
    ps aux --sort=-%cpu | head -n 6 | tail -n 5|awk '{print "pid:"$2,"cpu_percent:"$3,"program_name:"$11}'|tee -a /var/log/performance_usage.log
	#cpu_top_5=$( ps aux|tail -n +2 |sort -k3 -nr|head -5)

	#显示内存使用率最高的前5个进程
	#mem_top_5=$(ps aux --sort=-%mem | head -n 6 | tail -n 5)
    ps aux --sort=-%mem | head -n 6 | tail -n 5|awk '{print "pid:"$2,"mem_percent:"$3,"program_name:"$11}'|tee -a /var/log/performance_usage.log

	#显示进程的总的信息，有多少个进程，有多少个进程在running 
	top -bn 1|grep "^Task"|awk '{print "total_processes:"$2,"running_processes:"$4}'|tee -a /var/log/performance_usage.log 
}
# 调用cpu_info函数
cpu_info

#调用mem_info函数
mem_info

#调用disk_info函数
disk_info
#调用process_info函数
process_info

